import sheep from '@/sheep'
import {
  isEmpty
} from 'lodash-es'

let areaMap = {

}
export function renameProperties(obj) {
  const newObj = {
    id: obj.regionCode,
    name: obj.regionName
  }

  switch (obj.regionLevel) {
    case 1:
      newObj.level = 'province'
      break
    case 2:
      newObj.level = 'city'
      break
    case 3:
      newObj.level = 'district'
      break
    default:
      newObj.level = obj.regionLevel
  }
  areaMap[newObj.id] = {
    ...newObj
  }
  if (obj.children && obj.children.length > 0) {
    newObj.children = obj.children.map(child => renameProperties(child))
  }

  return newObj
}

export function getAreaData() {
  if (isEmpty(uni.getStorageSync('areaData')) || isEmpty(uni.getStorageSync('areaMap'))) {
    areaMap = {}
    sheep.$api.app.cityData.cityList().then((res) => {
      if (res.code === '0') {
        const areaData = res.data.map(obj => renameProperties(obj))
        uni.setStorageSync('areaData', areaData)
        uni.setStorageSync('areaMap', areaMap)
      }
    })
  }
}
